import { Table, Checkbox, Space, message, Typography, Modal, Tooltip, Button, Tabs } from 'antd';
import React, { useState, useEffect, forwardRef, useImperativeHandle, useMemo } from 'react';

import datasetService from '@/api/services/datasetService';
import userService from '@/api/services/userService';
import { DatasetListItem, DatasetTypeEnum, LicenseEditionEnum } from '@/common/types';
import { SvgIcon } from '@/components/icon';
import useWindowWidth from '@/hooks/event/use-window-width';
import usePermission from '@/hooks/event/usePermission';
import DeleteConfirmModal from '@/pages/datasets/components/DeleteConfirmModal';

import '../styles/permissionTable.css';
import PermissionTree from './PermissionTree';
import type { CheckboxChangeEvent } from 'antd/es/checkbox';



import { useUserInfo } from '@/store/userStore';

import cloneDeep from 'lodash/cloneDeep';
import uniq from 'lodash/uniq';

import {
  useDatasetFlag,
  useApiFlag,
  useConfigActions,
  useInitializeData,
} from '@/store/configStore';
import { useRoleManage } from '@/store/roleManageStore';

import {
  PlusCircleOutlined,
  MinusCircleOutlined,
  RightOutlined,
  DownOutlined,
  EyeOutlined,
  EyeInvisibleOutlined,
  DeleteOutlined,
} from '@ant-design/icons';

// 输入数据的类型定义
interface Permission {
  dataset_id?: string;
  action: string;
  resource_id: string;
  resource_type: string;
}

export interface Role {
  id: string;
  code: string;
  name: string;
  description: string;
  permissions: Permission[];
  children?: Role[] | undefined;
}

// 输出数据的类型定义
interface TransformedData {
  [key: string]: Permission[];
}

type Props = {
  onRoleRefresh?: () => void;
  roleSelected?: string;
};

const PermissionTable = forwardRef((props: Props, ref) => {
  const { role: userRole } = useUserInfo();
  const { Text } = Typography;
  const [roleList, setRoleList] = useState<Role[]>([]);
  const [dataset, setDataset] = useState<any[]>([]);

  const [policies, setPolicies] = useState<Permission[][]>([]);
  const [policiesAdmin, setPoliciesAdmin] = useState<Permission[][]>([]);

  const { isPc } = useWindowWidth();
  const [expandedRowKeys, setExpandedRowKeys] = useState<React.Key[]>([]);
  const [isExpandAll, setIsExpandAll] = useState<boolean>(false);
  const [isDataLoading, setIsDataLoading] = useState<boolean>(false);

  const [dataSource, setDataSource] = useState<any[]>([]);
  const [dataFilter, setDataFilter] = useState<any[]>([]);
  const [isDataFilter, setIsDataFilter] = useState<boolean>(false);

  const [showConfirmDelete, setShowConfirmDelete] = useState(false);
  const [roleToDelete, setRoleToDelete] = useState<Role>({});

  const [showRoleConfirm, setRoleShowConfirm] = useState(false);
  const [childrenRole, setChildrenRole] = useState([]);

  const [permissionTab, setPermissionTab] = useState('dataset');
  const [apiSource, setApiSource] = useState<any[]>([]);
  const [datasetSource, setDatasetSource] = useState<any[]>([]);
  const { isEnableRoleConditions } = useRoleManage();
  // const isEnableRoleConditions = false;

  const isSelectAllSupport = false;

  const datasetFlag = useDatasetFlag();
  const apiFlag = useApiFlag();
  const { isAdmin, isInManager } = usePermission();
  const { fetchPermitFlag } = useConfigActions();

  const initializeData = useInitializeData();
  const isDisabled = initializeData?.license_edition != LicenseEditionEnum.custom;

  // useEffect(() => {
  //   if (isAdmin) {
  //     return
  //   }
  //   if (!datasetFlag && apiFlag) {
  //     setPermissionTab(DatasetTypeEnum.api);
  //     setDataSource(cloneDeep(apiSource));
  //     setDataFilter(cloneDeep(apiSource));
  //   }
  //   if (!datasetFlag && !apiFlag) {
  //     setPermissionTab('sharelink');
  //   }
  // }, [apiSource, datasetFlag, apiFlag]);

  const isInRoleCode = (
    roleCode: string | string[] | undefined,
    roleCodeTarget: string,
  ): boolean => {
    if (!roleCode && !props?.roleSelected) {
      return false;
    }
    if (props?.roleSelected) {
      return props?.roleSelected === roleCodeTarget;
    }
    if (Array.isArray(roleCode)) {
      return roleCode.includes(roleCodeTarget);
    }
    return roleCode === roleCodeTarget;
  };

  const deleteRole = async (role: Role) => {
    try {
      const deleteIdList = [role?.id];
      function addChildrenIds(children: Role[] | undefined) {
        if (children && children.length > 0) {
          children.forEach((child) => {
            deleteIdList.push(child.id);
            addChildrenIds(child?.children);
          });
        }
      }
      addChildrenIds(role?.children);

      await userService.deleteRole(role?.id);
      message.success('删除角色成功');

      const updatedRoleList = roleList.filter((r) => !deleteIdList.includes(r?.id));
      setRoleList(updatedRoleList);

      setShowConfirmDelete(false);
      props?.onRoleRefresh && props?.onRoleRefresh();
    } catch (error) {
      console.error('Error deleting role:', error);
    }
  };

  // 递归勾选所有子节点
  const recursivelyCheckChildren = (
    policies: Permission[][],
    colIndex: number,
    children: any[],
  ) => {
    children.forEach((child) => {
      const policyList = policies[colIndex].map((i) => i?.resource_id);
      if (!policyList.includes(child.resource_id)) {
        policies[colIndex].push(child);
        console.log(child?.path);
        const childPath = child?.path?.filter((i: any) => i.type == 'folder') || [];
        for (const parent of childPath) {
          console.log(parent);
          if (!policies[colIndex].map((i) => i?.resource_id)?.includes(parent.resource_id)) {
            policies[colIndex].push(parent);
          }
        }
      }
      if (child?.children && child?.children?.length > 0) {
        recursivelyCheckChildren(policies, colIndex, child?.children);
      }
    });
  };

  // 递归取消勾选所有子节点
  const recursivelyUncheckChildren = (
    policies: Permission[][],
    colIndex: number,
    children: any[],
  ) => {
    children.forEach((child) => {
      const policyList = policies[colIndex].map((i) => i?.resource_id);
      console.log(child);
      console.log(policyList);
      const index = policyList.indexOf(child.resource_id);
      if (index !== -1) {
        console.log(index);
        policies[colIndex].splice(index, 1);
      }
      if (child?.children && child?.children?.length > 0) {
        recursivelyUncheckChildren(policies, colIndex, child?.children);
      }
    });
  };

  const transformData = (roles: Role[], action: string): TransformedData => {
    return roles.reduce((acc: TransformedData, role: Role) => {
      const { code, permissions } = role;
      acc[code] = permissions?.filter((permission) => permission.action != action);
      return acc;
    }, {});
  };

  const updateChildRole = (data) => {
    const allChildrenIds = uniq(
      data.flatMap((i: Role) => i?.children?.map((child: Role) => child.id) || []),
    );
    const allDataIds = data.map((i: Role) => i.id);
    const uniqueChildrenIds = allChildrenIds.filter((id) => !allDataIds.includes(id));

    setChildrenRole(uniqueChildrenIds);
  };

  const getRoleList = async () => {
    try {
      setIsDataLoading(true);
      const datasetAdmin = await datasetService.datasetList({ action: 'admin', parentId: null });
      console.log(datasetAdmin);
      setDataset(datasetAdmin);

      const data = await userService.getRolePermissions();

      // const userData = data.filter((i: Role) => i?.id == userRole?.id);
      const filtered = data.filter((i: Role) => i?.id == userRole?.id);
      const userData = filtered.length > 0 ? [filtered[0]] : [];

      if (isPc) {
        setRoleList(userData);
      }

      console.log(transformData(userData, 'admin'));
      setPolicies(Object.values(transformData(userData, 'admin')));
      setPoliciesAdmin(Object.values(transformData(userData, 'read')));

      updateChildRole(data);
    } catch (error) {
    } finally {
      setIsDataLoading(false);
    }
  };

  useEffect(() => {
    fetchPermitFlag();
    getRoleList();
  }, []);

  const updateRoleList = async (updateRoleList = []) => {
    const updateRoleIdList = updateRoleList?.map((item) => item?.id);
    const roleIdList = roleList?.map((item) => item?.id);
    if (JSON.stringify(updateRoleIdList) === JSON.stringify(roleIdList)) {
      return;
    }

    const data = await userService.getRolePermissions();
    updateChildRole(data);

    if (updateRoleList) {
      setRoleList(updateRoleList);
      setPolicies(Object.values(transformData(updateRoleList, 'admin')));
      setPoliciesAdmin(Object.values(transformData(updateRoleList, 'read')));
    }
  };

  const handleCheckboxChangeAdminAll = (id: string, colIndex: number, allRowData: any[]) => {
    setPoliciesAdmin((prevPoliciesAdmin) => {
      const newPolicies = [...prevPoliciesAdmin];
      if (newPolicies[colIndex].length === allRowData.length) {
        newPolicies[colIndex] = []; // 取消全选
      } else {
        newPolicies[colIndex] = allRowData; // 全选
      }
      userService.updateRolePermissions(id, {
        permissions: [
          ...transformDatasetIdsToPermissions(policies[colIndex], 'read'),
          ...transformDatasetIdsToPermissions(newPolicies[colIndex], 'admin'),
        ],
      });
      props?.onRoleRefresh && props?.onRoleRefresh();
      return newPolicies;
    });
  };

  const handleCheckboxChangeAll = (id: string, colIndex: number, allRowData: any[]) => {
    setPolicies((prevPolicies) => {
      const newPolicies = [...prevPolicies];
      if (newPolicies[colIndex].length === allRowData.length) {
        newPolicies[colIndex] = []; // 取消全选
      } else {
        newPolicies[colIndex] = allRowData; // 全选
      }
      userService.updateRolePermissions(id, {
        permissions: [
          ...transformDatasetIdsToPermissions(newPolicies[colIndex], 'read'),
          ...transformDatasetIdsToPermissions(policiesAdmin[colIndex], 'admin'),
        ],
      });
      props?.onRoleRefresh && props?.onRoleRefresh();
      return newPolicies;
    });
  };

  useImperativeHandle(ref, () => ({
    updateRoleList,
  }));

  const transformDatasetIdsToPermissions = (
    datasetIds: Permission[],
    action: string,
  ): Permission[] => {
    return datasetIds?.map((datasetItem) => ({
      action,
      resource_type: datasetItem?.resource_type,
      resource_id: datasetItem?.resource_id,
    }));
  };

  const handleCheckboxChange = (rowIndex: string, colIndex: number) => (e: CheckboxChangeEvent) => {
    const { id } = roleList[colIndex];
    const dataSelect = allRowData.filter((i) => i.key == rowIndex)?.[0];
    setPolicies((prevPolicies) => {
      const newPolicies = [...prevPolicies];
      if (e.target.checked) {
        if (!newPolicies?.[colIndex]?.map((i) => i.resource_id).includes(rowIndex)) {
          newPolicies?.[colIndex]?.push(dataSelect);
        }
        const childPath = dataSelect?.path || [];
        for (const parent of childPath) {
          if (!newPolicies[colIndex].map((i) => i?.resource_id)?.includes(parent.resource_id)) {
            newPolicies?.[colIndex]?.push(parent);
          }
        }

        if (dataSelect?.children && dataSelect?.children.length > 0) {
          // 递归勾选所有子节点
          recursivelyCheckChildren(newPolicies, colIndex, dataSelect.children);
        }
      } else {
        const resourceIdList = newPolicies[colIndex]?.map((i) => i.resource_id);
        const index = resourceIdList.indexOf(rowIndex);
        if (index !== -1) {
          newPolicies[colIndex].splice(index, 1);
        }
        if (dataSelect?.children && dataSelect?.children.length > 0) {
          // 递归取消勾选所有子节点
          recursivelyUncheckChildren(newPolicies, colIndex, dataSelect.children);
        }
      }
      userService.updateRolePermissions(id, {
        permissions: [
          ...transformDatasetIdsToPermissions(newPolicies[colIndex], 'read'),
          ...transformDatasetIdsToPermissions(policiesAdmin[colIndex], 'admin'),
        ],
      });
      props?.onRoleRefresh && props?.onRoleRefresh();

      return newPolicies;
    });
  };

  const handleCheckboxChangeAdmin =
    (rowIndex: string, colIndex: number) => (e: CheckboxChangeEvent) => {
      const { id } = roleList[colIndex];
      const dataSelect = allRowData.filter((i) => i.key == rowIndex)?.[0];

      setPoliciesAdmin((prevPolicies) => {
        const newPolicies = [...prevPolicies];
        if (e.target.checked) {
          if (!newPolicies?.[colIndex]?.map((i) => i.resource_id).includes(rowIndex)) {
            newPolicies?.[colIndex]?.push(dataSelect);
          }
          const childPath = dataSelect?.path || [];
          for (const parent of childPath) {
            if (!newPolicies[colIndex].map((i) => i?.resource_id)?.includes(parent.resource_id)) {
              newPolicies?.[colIndex]?.push(parent);
            }
          }
          if (dataSelect?.children && dataSelect?.children.length > 0) {
            // 递归勾选所有子节点
            recursivelyCheckChildren(newPolicies, colIndex, dataSelect.children);
          }
        } else {
          const resourceIdList = newPolicies[colIndex]?.map((i) => i.resource_id);
          const index = resourceIdList.indexOf(rowIndex);
          if (index !== -1) {
            newPolicies[colIndex].splice(index, 1);
          }
          if (dataSelect?.children && dataSelect?.children.length > 0) {
            // 递归取消勾选所有子节点
            recursivelyUncheckChildren(newPolicies, colIndex, dataSelect.children);
          }
        }
        userService.updateRolePermissions(id, {
          permissions: [
            ...transformDatasetIdsToPermissions(policies[colIndex], 'read'),
            ...transformDatasetIdsToPermissions(newPolicies[colIndex], 'admin'),
          ],
        });
        props?.onRoleRefresh && props?.onRoleRefresh();
        return newPolicies;
      });
    };

  const filterByResourceIds = (data: any, resourceIds: string[], resourceIdAdmins: string[]) => {
    const filterChildren = (items: any) => {
      return items?.filter((item: any) => {
        // 如果是 folder，递归处理其 children
        if (item?.children && item?.resource_type == 'folder') {
          // 递归过滤 children
          item.children = filterChildren(item.children);
          return !!(
            item.children?.length > 0 ||
            resourceIds?.includes(item?.id) ||
            resourceIdAdmins?.includes(item?.id)
          );
        }
        // 如果是 file，判断是否满足条件
        return resourceIds?.includes(item?.id) || resourceIdAdmins?.includes(item?.id);
      });
    };

    return filterChildren(data);
  };

  // 构建表格数据
  const columns = [
    {
      title: () => (
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <span style={{ textAlign: 'center', flex: 1 }}>
            {permissionTab == DatasetTypeEnum.dataset ? '知识库列表' : '数据接口列表'}
          </span>
          <div
            style={{
              paddingRight: '20px',
              cursor: 'pointer',
            }}
            onClick={() => {
              if (isDataFilter) {
                setDataFilter(dataSource);
              } else {
                const resourceIds = Array.from(new Set(policies.flat().map((i) => i.resource_id)));
                const resourceIdAdmins = Array.from(
                  new Set(policiesAdmin.flat().map((i) => i.resource_id)),
                );
                const filterData = filterByResourceIds(
                  cloneDeep(dataFilter),
                  resourceIds,
                  resourceIdAdmins,
                );
                setDataFilter(filterData);
              }
              setIsDataFilter(!isDataFilter);
            }}
          >
            {isDataFilter ? (
              <Tooltip
                title={
                  permissionTab == DatasetTypeEnum.dataset ? '展示所有知识库' : '展示所有数据接口'
                }
              >
                <EyeInvisibleOutlined />
              </Tooltip>
            ) : (
              <Tooltip
                title={
                  permissionTab == DatasetTypeEnum.dataset
                    ? '仅展示选中的知识库'
                    : '仅展示选中的数据接口'
                }
              >
                <EyeOutlined />
              </Tooltip>
            )}
          </div>
          <div
            style={{
              cursor: 'pointer',
            }}
            onClick={() => {
              toggleExpandAll();
            }}
          >
            {/* <SvgIcon icon="ic_rj_plus_circle" size="15" /> */}
            {isExpandAll ? (
              <Tooltip title="折叠文件夹">
                <MinusCircleOutlined />
              </Tooltip>
            ) : (
              <Tooltip title="展开文件夹">
                <PlusCircleOutlined />
              </Tooltip>
            )}
          </div>
        </div>
      ),
      dataIndex: 'permission',
      key: 'permission',
      width: isPc ? 300 : '50%',
      ellipsis: true,
      render: (_, record: any) => {
        return (
          <div className="flex items-center justify-between">
            <div
              className="flex items-center"
              style={{
                width: record.type == 'folder' ? '75%' : '100%',
                cursor: record.type == 'folder' ? 'pointer' : undefined,
              }}
              onClick={() => {
                onExpand(!expandedRowKeys.includes(record?.key), record);
              }}
            >
              <div
                style={{
                  background: 'transparent',
                  color: record?.type != 'folder' ? 'rgb(191, 99, 255)' : 'rgb(78, 135, 255)',
                  fontSize: record?.type == 'folder' ? '18px' : '18px',
                  flexShrink: 0,
                }}
                className="flex h-[32px] w-[32px] items-center justify-center rounded-lg"
              >
                {record.type == 'folder' ? (
                  <SvgIcon icon="ri--folder-2-fill" size={24} color="#FFCA28" />
                ) : record.type == DatasetTypeEnum.api ? (
                  <SvgIcon color="#33ADFF" icon="tdesign--folder-setting-filled" size={24} />
                ) : (
                  <SvgIcon icon="mdi--folder-zip" size={24} color="#3F70FF" />
                )}
              </div>
              <Text
                ellipsis
                style={{
                  paddingLeft: '10px',
                  fontSize: '16px',
                  color: '#515151',
                  overflow: 'hidden',
                  whiteSpace: 'nowrap',
                  textOverflow: 'ellipsis',
                  maxWidth: roleList?.length > 0 ? '400px' : 'unset',
                }}
              >
                {record.permission}
              </Text>
            </div>
            {isPc && record.type == 'folder' && (
              <div
                style={{
                  minWidth: '43px',
                  width: '43px',
                  height: '22px',
                  background: '#E5DCFF',
                  borderRadius: '11px',
                  display: 'flex',
                  justifyContent: 'center',
                  flexShrink: 0,
                }}
              >
                {record.count > 99 ? '99+' : record?.count}
              </div>
            )}
          </div>
        );
      },
    },
    ...roleList.map((role: Role, colIndex) => ({
      title: () => (
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              width: '100%',
            }}
          >
            <span className="flex w-full items-center justify-center">
              <div className="flex items-center justify-center">
                <SvgIcon
                  icon="rj-park-solid--people"
                  size={18}
                  style={{
                    marginRight: '10px',
                    color: '#4AB5DC',
                  }}
                />
              </div>
              {role?.name}
            </span>
            {/* {![userRole?.code].includes(role?.code) && ( */}
            {/* {(childrenRole.includes(role?.id) || userRole?.code=='admin') && role?.code != 'admin' && ( */}

            {!isEnableRoleConditions && childrenRole.includes(role?.id) && (
              <div
                style={{
                  cursor: 'pointer',
                }}
                onClick={() => {
                  setRoleToDelete(role);
                  setShowConfirmDelete(true);
                  // setRoleShowConfirm(true)
                }}
              >
                {/* <SvgIcon icon="ic_rj_delete" size="15" /> */}
                {/* <MinusCircleOutlined /> */}
                <Tooltip title="删除角色">
                  {/* <SvgIcon icon="ic_rj_delete_role" size="15" /> */}
                  {/* <UserOutlined /> */}
                  <DeleteOutlined style={{ color: 'red' }} />
                </Tooltip>
              </div>
            )}
          </div>
          {isSelectAllSupport && (
            <div style={{ display: 'flex', alignItems: 'center', gap: '8px', marginTop: '8px' }}>
              <Checkbox
                indeterminate={
                  policiesAdmin[colIndex].length > 0 &&
                  policiesAdmin[colIndex].length < allRowData.length
                }
                checked={policiesAdmin[colIndex].length === allRowData.length}
                onChange={() =>
                  handleCheckboxChangeAdminAll(roleList[colIndex]?.id, colIndex, allRowData)
                }
              >
                管理全选
              </Checkbox>
              <Checkbox
                indeterminate={
                  policies[colIndex].length > 0 && policies[colIndex].length < allRowData.length
                }
                checked={policies[colIndex].length === allRowData.length}
                onChange={() =>
                  handleCheckboxChangeAll(roleList[colIndex]?.id, colIndex, allRowData)
                }
              >
                问答全选
              </Checkbox>
              <Button
                size="small"
                type="default"
                onClick={() => {
                  const policyReset = roleList[colIndex].permissions?.filter(
                    (i) => i?.action == 'read',
                  );
                  const policyAdminReset = roleList[colIndex].permissions?.filter(
                    (i) => i?.action == 'admin',
                  );

                  setPolicies((prevPolicies) => {
                    const newPolicies = [...prevPolicies];
                    newPolicies[colIndex] = policyReset;
                    return newPolicies;
                  });
                  setPoliciesAdmin((prevPolicies) => {
                    const newPolicies = [...prevPolicies];
                    newPolicies[colIndex] = policyAdminReset;
                    return newPolicies;
                  });
                  userService.updateRolePermissions(roleList[colIndex]?.id, {
                    permissions: [
                      ...transformDatasetIdsToPermissions(policyReset, 'read'),
                      ...transformDatasetIdsToPermissions(policyAdminReset, 'admin'),
                    ],
                  });
                  props?.onRoleRefresh && props?.onRoleRefresh();
                }}
              >
                重置
              </Button>
            </div>
          )}
        </div>
      ),
      dataIndex: role.code,
      key: role.id,
      render: (_: any, record: any) => (
        <Space size="large" style={{ justifyContent: 'space-around', width: '100%' }}>
          <Checkbox
            checked={
              isAdmin && role?.code == 'admin'
                ? true
                : policiesAdmin?.[colIndex]?.map((i) => i.resource_id)?.includes(record.key) ||
                false
            }
            onChange={handleCheckboxChangeAdmin(record.key, colIndex)}
            disabled={isInRoleCode(userRole?.code, role?.code)}
            style={{
              color:
                policiesAdmin?.[colIndex]?.map((i) => i.resource_id)?.includes(record.key) || false
                  ? '#6640FF'
                  : '#BBBBBE',
            }}
          >
            管理
          </Checkbox>

          <Checkbox
            checked={policies?.[colIndex]?.map((i) => i.resource_id)?.includes(record.key) || false}
            onChange={handleCheckboxChange(record.key, colIndex)}
            style={{
              color:
                policies?.[colIndex]?.map((i) => i.resource_id)?.includes(record.key) || false
                  ? '#6640FF'
                  : '#99999e',
            }}
          >
            问答
          </Checkbox>
        </Space>
      ),
    })),
  ];

  useEffect(() => {
    const dataSourceTemp: any = [];
    const dataSourceTemp2: any = [];

    function processPermission(permission: DatasetListItem) {
      const item = {
        key: permission?._id,
        id: permission?._id,
        resource_id: permission?._id,
        resource_type: permission?.type,
        permission: permission?.name,
        type: permission?.type,
        children: [],
        count: permission?.count || 0,
      };

      if (permission?.children && permission?.children?.length > 0) {
        item.children = permission.children.map((child: DatasetListItem) =>
          processPermission(child),
        );
      }

      return item;
    }

    dataset.forEach((permission) => {
      permission?.type != DatasetTypeEnum.api && dataSourceTemp.push(processPermission(permission));
      permission?.type == DatasetTypeEnum.api &&
        dataSourceTemp2.push(processPermission(permission));
      // ['dataset', 'folder'].includes(permission?.type) && dataSourceTemp.push(processPermission(permission));
      // ['api', 'folder'].includes(permission?.type) && dataSourceTemp2.push(processPermission(permission));
    });
    console.log(dataSourceTemp);
    console.log(dataSourceTemp2);
    setDatasetSource(dataSourceTemp);
    setApiSource(dataSourceTemp2);
    setDataSource(dataSourceTemp);
    setDataFilter(dataSourceTemp);
  }, [dataset]);

  const rowClassName = (record: any) => {
    return record?.type === 'folder' ? 'folder-row' : '';
  };

  const allRowData = useMemo(() => {
    const keys: any = [];

    const traverse = (data, path) => {
      data.forEach((item) => {
        const currentPath = [
          ...path,
          {
            key: item.key,
            type: item.type,
            resource_id: item.resource_id,
            resource_type: item.resource_type,
          },
        ]; // 当前路径
        item.path = currentPath; // 将路径信息添加到节点中
        keys.push(item);

        if (item?.children) {
          traverse(item.children, currentPath);
        }
      });
    };

    traverse(dataSource, []); // 初始路径为空数组

    return keys;
  }, [dataSource]);

  const allRowKeys = useMemo(() => {
    return allRowData.map((i) => i.key);
  }, [allRowData]);

  const toggleExpandAll = () => {
    if (!isExpandAll) {
      setExpandedRowKeys(allRowKeys);
      setIsExpandAll(true);
    } else {
      setExpandedRowKeys([]);
      setIsExpandAll(false);
    }
  };

  const onExpand = (expanded, record) => {
    if (expanded) {
      // 展开行
      setExpandedRowKeys([...expandedRowKeys, record.key]);
    } else {
      // 合并行
      setExpandedRowKeys(expandedRowKeys.filter((key) => key !== record.key));
    }
  };

  const customExpandIcon = ({ expanded, onExpand, record }) => {
    if (record?.type != 'folder') {
      return <Text className="expand-custome" />;
    }
    return expanded ? (
      <DownOutlined className="expand-custome" onClick={(e) => onExpand(record, e)} />
    ) : (
      <RightOutlined className="expand-custome" onClick={(e) => onExpand(record, e)} />
    );
  };

  useEffect(() => {
    console.log(permissionTab);
    if (permissionTab == DatasetTypeEnum.dataset) {
      setDataSource(cloneDeep(datasetSource));
      setDataFilter(cloneDeep(datasetSource));
    }
    if (permissionTab == DatasetTypeEnum.api) {
      setDataSource(cloneDeep(apiSource));
      setDataFilter(cloneDeep(apiSource));
    }
  }, [permissionTab]);

  return (
    <>
      <DeleteConfirmModal
        visible={showConfirmDelete}
        text={
          <span
            dangerouslySetInnerHTML={{
              __html: `确认删除角色 <strong>${roleToDelete?.name}</strong> ${roleToDelete?.children?.length > 0 ? '及其<strong>子角色</strong>' : ''
                } 吗？`,
            }}
          />
        }
        onCancel={() => setShowConfirmDelete(false)}
        onConfirm={() => deleteRole(roleToDelete)}
      />
      <Modal
        open={showRoleConfirm}
        onCancel={() => {
          setRoleShowConfirm(false);
        }}
        closable={false}
        footer={false}
      >
        <PermissionTree />
      </Modal>

      <Tabs
        // tabPosition={isPc ? (isInManager ? 'top' : 'left') : 'top'}
        tabPosition="top"
        onTabClick={(item: string) => {
          setIsDataFilter(false);
          setPermissionTab(item);
        }}
        defaultValue={permissionTab}
        items={[
          {
            key: 'dataset',
            label: (
              <span>
                <SvgIcon
                  icon="ri--book-2-fill"
                  size={30}
                  style={{
                    padding: '5px',
                    color: '#3F70FF',
                  }}
                />
                知识库
              </span>
            ),
            children: (
              <Table
                loading={isDataLoading}
                className="permission"
                indentSize={20}
                columns={columns}
                dataSource={dataFilter}
                pagination={false}
                bordered
                scroll={{ x: isPc ? 'max-content' : undefined }}
                rowClassName={rowClassName}
                expandable={{
                  expandedRowKeys,
                  onExpand,
                  expandIcon: customExpandIcon,
                }}
              />
            ),
          },
          ...(isDisabled
            ? []
            : [
              {
                key: 'function',
                label: (
                  <span>
                    <SvgIcon
                      icon="icon-park-solid--api"
                      size={30}
                      style={{
                        padding: '5px',
                        color: '#33ADFF',
                      }}
                    />
                    数据接口
                  </span>
                ),
                children: (
                  <Table
                    loading={isDataLoading}
                    className="permission"
                    indentSize={20}
                    columns={columns}
                    dataSource={dataFilter}
                    pagination={false}
                    bordered
                    scroll={{ x: isPc ? 'max-content' : undefined }}
                    rowClassName={rowClassName}
                    expandable={{
                      expandedRowKeys,
                      onExpand,
                      expandIcon: customExpandIcon,
                    }}
                  />
                ),
              },
            ]),
          // {
          //   key: 'sharelink',
          //   label: (
          //     <span>
          //       <SvgIcon
          //         icon="share"
          //         size={30}
          //         style={{
          //           padding: '5px',
          //           color: '#3783eb',
          //         }}
          //       />
          //       分享链接
          //     </span>
          //   ),
          //   children: <SharelinkPage />,
          // },
        ]}
      />

      {/* <Table
        loading={isDataLoading}
        className="permission"
        indentSize={20}
        columns={columns}
        dataSource={dataFilter}
        pagination={false}
        bordered
        scroll={{ x: isPc ? 'max-content' : undefined }}
        rowClassName={rowClassName}
        expandable={{
          expandedRowKeys,
          onExpand,
          expandIcon: customExpandIcon,
        }}
      /> */}
    </>
  );
});

export default PermissionTable;
